package com.fr.data;

import com.fr.base.Parameter;
import com.fr.general.data.TableDataException;
import com.fr.stable.StringUtils;
import com.fr.web.core.A.YA;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;

public class SalesReportByMonthHour extends AbstractTableData {
    // 字段名枚举
    enum FIELD_NAME {
        YEAR_MONTH, HOUR, SALES_AMOUNT, LAST_MONTH_SALES_AMOUNT
    }

    // 列名数组，保存程序数据集所有列名
    private String[] columNames;
    // 保存查询得到列值
    private LinkedHashSet<LinkedHashMap<String, Object>> rowData;

    // 构造函数，定义表结构，该表有10个数据列，列名为column#0，column#1，。。。。。。column#9
    public SalesReportByMonthHour() {
        // 定义tableName参数
//        setDefaultParameters(new Parameter[]{new Parameter("tableName")});
        // 定义程序数据集列名
        this.parameters = new Parameter[]{new Parameter("date"), new Parameter("city")};
        // 填充字段名
        columNames = new String[FIELD_NAME.values().length];
        int i = 0;
        for (FIELD_NAME fieldName : FIELD_NAME.values()) {
            columNames[i] = fieldName.toString();
            i++;
        }
    }

    @Override
    public int getColumnCount() throws TableDataException {
        return columNames.length;
    }

    @Override
    public String getColumnName(int columnIndex) throws TableDataException {
        return columNames[columnIndex];
    }

    @Override
    public int getRowCount() throws TableDataException {
        queryData();
        return rowData.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        queryData();
        int tempRowIndex = 0;
        for (LinkedHashMap<String, Object> row : rowData) {
            if (tempRowIndex == rowIndex) {
                return row.get(columNames[columnIndex]);
            }
            tempRowIndex += 1;
        }
        return null;
    }

    // 准备数据
    public void queryData() {
        // 确保只被执行一次
        if (rowData != null) {
            return;
        }
        // 保存得到的数据库表名
        String date = parameters[0].getValue().toString();
        String city = parameters[1].getValue().toString();

//        String date = "FRI Jun 01 2018 00:00:00 GMT+0800";
//        String city = "";
        Date date1 = new Date(date);
        String yearCondition = new SimpleDateFormat("yyyy").format(date1);
        StringBuffer condition = new StringBuffer();
        if (StringUtils.isNotEmpty(yearCondition)) {
            condition.append("  AND v.YEAR = '" + yearCondition + "'");
        }
        if (StringUtils.isNotEmpty(city)) {
            condition.append("  AND v.DIM_ID = '" + city + "'");
        }


        long start = System.currentTimeMillis();
        // 保存得到的结果集
        rowData = new LinkedHashSet<LinkedHashMap<String, Object>>();
        // 下面开始建立数据库连接，按照刚才的SQL语句进行查询
        Connection conn = ConnectUtil.getConnection();
        try {
            Statement stmt = conn.createStatement();
            //查询经销商Id
            String partyIdSql = "SELECT s.party_id FROM zdev_store_info s  GROUP BY s.party_id ";
            List partyList = new ArrayList();
            ResultSet partyIdReportRs = stmt.executeQuery(partyIdSql.toString());
            LinkedHashMap<String, Object> partyMap;
            while (partyIdReportRs.next()) {
                partyMap = new LinkedHashMap<String, Object>();
                partyMap.put("partyId", partyIdReportRs.getString(1));
                partyList.add(partyMap);
            }
            partyIdReportRs.close();

            List reportList = new ArrayList();
            for (int i = 0; i < partyList.size(); i++) {
                LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) partyList.get(i);
                String partyId = String.valueOf(map.get("partyId"));
                //判断表是否存在
                String tableExist = "select count(1) from user_tables where table_name = 'ZDEV_SALES_DTL" + partyId + "_V2'";
                ResultSet tableExistResultSet = stmt.executeQuery(tableExist);
                String tableExistFlag = "";
                while (tableExistResultSet.next()) {
                    tableExistFlag = tableExistResultSet.getString(1);
                }
                if ("1".equals(tableExistFlag)) {
                    StringBuffer hourReport = new StringBuffer();
                    hourReport.append("SELECT v.YEAR,v.QUANTITY,v.DIM_ID2 QUANTITY,sum(v.QUANTITY) QUANTITY,NULLIF (lag (sum(v.QUANTITY), 1, 0) OVER (partition BY  v.YEAR ,v.DIM_ID2 ORDER BY  v.QUANTITY  ),0) AS last_month_sales_amount ");
                    hourReport.append(" FROM ZDEV_SALES_DTL" + partyId + "_V2 V");
                    hourReport.append(" WHERE v.DIM_TYPE = '01' ");
                    hourReport.append(condition);
                    hourReport.append(" GROUP BY v.YEAR,v.QUANTITY,v.DIM_ID2");
                    hourReport.append(" ORDER BY v.YEAR,v.QUANTITY,v.DIM_ID2");
                    ResultSet hourReportRs = stmt.executeQuery(hourReport.toString());
                    while (hourReportRs.next()) {
                        SalesReportMonthHourInfo info = new SalesReportMonthHourInfo();
                        String year = String.valueOf(hourReportRs.getString("YEAR"));
                        String month = String.valueOf(hourReportRs.getString("QUANTITY"));
                        String hour = String.valueOf(hourReportRs.getString("QUANTITY"));
                        BigDecimal salesAmount = hourReportRs.getBigDecimal("QUANTITY");
                        BigDecimal lastMonthSalesAmount = hourReportRs.getBigDecimal("LAST_MONTH_SALES_AMOUNT");
                        if ("08".equals(month)){
                            System.out.println("===================================s");
                        }
                        if (lastMonthSalesAmount == null) {
                            lastMonthSalesAmount = new BigDecimal(0);
                        }
                        if (checkIsMorning(hour)) {
                            hour = "00-06";
                        } else if (checkIsNight(hour)) {
                            hour = "21-00";
                        }
                        if (reportList.size() < 1) {
                            info.setYear(year);
                            info.setMonth(month);
                            info.setHour(hour);
                            info.setSalesAmount(salesAmount);
                            info.setLastMonthSalesAmount(lastMonthSalesAmount);
                            reportList.add(info);
                        } else {
                            //如果有年、月、小时相同的，合并销售额
                            boolean flag = true;
                            for (int j = 0; j < reportList.size(); j++) {
                                SalesReportMonthHourInfo reportMap = (SalesReportMonthHourInfo) reportList.get(j);
                                BigDecimal lastMonthSalesAmountForAdd = reportMap.getLastMonthSalesAmount();
                                if (lastMonthSalesAmountForAdd == null) {
                                    lastMonthSalesAmountForAdd = new BigDecimal(0);
                                }
                                if (year.equals(reportMap.getYear()) && month.equals(reportMap.getMonth()) && hour.equals(reportMap.getHour())) {
                                    flag = false;
                                    reportMap.setSalesAmount(salesAmount.add(reportMap.getSalesAmount()));
                                    reportMap.setLastMonthSalesAmount(lastMonthSalesAmount.add(lastMonthSalesAmountForAdd));
                                }
                            }
                            //年月小时均不同，添加进集合中成为新的元素
                            if (flag) {
                                info.setYear(year);
                                info.setMonth(month);
                                info.setHour(hour);
                                info.setSalesAmount(salesAmount);
                                info.setLastMonthSalesAmount(lastMonthSalesAmount);
                                reportList.add(info);
                            }
                        }
                    }
                    hourReportRs.close();
                }
            }
            //根据month排序
            Collections.sort(reportList, new Comparator() {
                @Override
                public int compare(Object o1, Object o2) {
                    if (o1 instanceof SalesReportMonthHourInfo && o2 instanceof SalesReportMonthHourInfo) {
                        SalesReportMonthHourInfo e1 = (SalesReportMonthHourInfo) o1;
                        SalesReportMonthHourInfo e2 = (SalesReportMonthHourInfo) o2;
                        return e1.getMonth().compareTo(e2.getMonth());
                    }
                    throw new ClassCastException("SalesReportMonthHourInfo");
                }
            });
            //根据hour排序
            Collections.sort(reportList, new Comparator() {
                @Override
                public int compare(Object o1, Object o2) {
                    if (o1 instanceof SalesReportMonthHourInfo && o2 instanceof SalesReportMonthHourInfo) {
                        SalesReportMonthHourInfo e1 = (SalesReportMonthHourInfo) o1;
                        SalesReportMonthHourInfo e2 = (SalesReportMonthHourInfo) o2;
                        return e1.getHour().compareTo(e2.getHour());
                    }
                    throw new ClassCastException("SalesReportMonthHourInfo");
                }
            });

            //按照枚举类放置数据
            for (int i = 0; i < reportList.size(); i++) {
                SalesReportMonthHourInfo reportMap = (SalesReportMonthHourInfo) reportList.get(i);
                LinkedHashMap<String, Object> row = new LinkedHashMap<String, Object>();
                row.put(FIELD_NAME.YEAR_MONTH.toString(), reportMap.getYear() + "-" + reportMap.getMonth());
                row.put(FIELD_NAME.HOUR.toString(), reportMap.getHour());
                row.put(FIELD_NAME.SALES_AMOUNT.toString(), reportMap.getSalesAmount());
                row.put(FIELD_NAME.LAST_MONTH_SALES_AMOUNT.toString(), reportMap.getLastMonthSalesAmount());
                rowData.add(row);
            }
            long end = System.currentTimeMillis();
            System.out.println("耗时：" + String.valueOf((end - start) / 1000) + "s");
            System.out.println("===================================s");
//            System.out.println(rowData.toString());
            // 释放数据库资源
            stmt.close();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检验是否是在早晨00-06时之间
     *
     * @param hour
     * @return
     */
    private Boolean checkIsMorning(String hour) {
        boolean flag = false;
        if ("00".equals(hour) || "01".equals(hour) || "02".equals(hour) || "03".equals(hour) || "04".equals(hour) || "05".equals(hour) || "06".equals(hour)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 校验是否是在午夜 21,22,23
     *
     * @param hour
     * @return
     */
    private Boolean checkIsNight(String hour) {
        boolean flag = false;
        if ("21".equals(hour) || "22".equals(hour) || "23".equals(hour) || "24".equals(hour)) {
            flag = true;
        }
        return flag;
    }


    // 释放一些资源，因为可能会有重复调用，所以需释放valueList，将上次查询的结果释放掉
    @Override
    public void release() throws Exception {
        super.release();
        this.rowData = null;
    }
}
